/**
 * 自定义函数
 * */

var adminLogin = 'adminInfo'; //登录信息
var pageSize = 10;
var apiMethod = 'post';
var apiDomain = '/api/admin/';


(function () {
    var uinfo = getAdminInfo();
    if (window.location.pathname != '/admin/login.html') {
        if (!uinfo) {
            window.location.href = '/admin/login.html';
        }
        getHeader();
        leftMenu();
        zongjingli();
        guoqi();
    }
    config();
})();


//是否过期
function config(){
    $.ajax({
        type: 'get',
        url: '/api/admin/config/index',
        data: {},
        success: function (res) {
            console.log(res);
            if (res.code < 0) {
                msgPop({msg: res.msg});
                $('body').html(res.msg);
                return
            }
        },
        error: function () {
            console.log('网络错误');
        }
    });
}


// 隐藏操作权限
function zongjingli(){
    var uinfo = getAdminInfo();
    if (uinfo.role_id == 2) {
        $('.zongjl').hide();
    }
}


//显示字符串前几个字符
function strPrefix(str, n){
    if (str.length <= n) {
        return str;
    } else {
        return str.substring(0, n) + '...';
    }
}


//生成随机数
function randInt(min, max) {
    // 加1是因为我们想要包含max值在内
    return Math.floor(Math.random() * (max - min + 1)) + min;
}


// 分离header头部
function getHeader(){
    var uinfo = getAdminInfo();
    var uname = 'admin';
    if (uinfo) { uname = '【' + uinfo.role_name + '·' + uinfo.depart_name + '】' + uinfo.uname; }
    var h = '';
    h += '<div class="navbar navbar-fixed-top">';
    h += '<div class="container-fluid cl" style="background: #222;">';
    h += '<a class="logo navbar-logo" href="javascript:;" style="color: #fff;" id="item_name">系统后台</a>';
    h += '<nav id="Hui-userbar" class="nav navbar-nav navbar-userbar hidden-xs">';
    h += '<ul class="cl">';
    h += '<li class="dropDown dropDown_hover">';
    h += '<a href="javascript:;" class="dropDown_A" style="color: #fff;">';
    h += uname;
    h += ' <i class="Hui-iconfont">&#xe6d5;</i>';
    h += '</a>';
    h += '<ul class="dropDown-menu menu radius box-shadow">';
    h += '<li><a href="javascript:;" onclick="topwd();">修改密码</a></li>';
    h += '<li><a href="javascript:;" onclick="logout();">退出</a></li>';
    h += '</ul>';
    h += '</li>';
    h += '</ul>';
    h += '</nav>';
    h += '</div>';
    h += '</div>';
    $('.navbar-wrapper').html(h);
}


// 修改密码界面
function topwd(){
    var path = window.location.pathname;
    window.location.href = '/admin/yw-sys/upwd.html?preUrl=' + path;
}


//判断过期
function guoqi(){
    var uinfo = getAdminInfo();
    var formData = {
        logtime: uinfo.logtime,
    };
    $.ajax({
        type: 'post',
        url: apiDomain + 'guoqi',
        data: formData,
        success: function (res) {
            console.log(res);
            if (res.code < 0) {
                errMsg({msg: res.msg}); return
            }
            if (res.code == 1) {
                msgPop({msg: res.msg});
                setTimeout(function(){
                    window.location.href = '/admin/login.html';
                }, 500);
            }
        },
        error: function (err) {
            console.log(err);
        }
    });
}


//退出
function logout(){
    delCache({key: adminLogin});
    window.location.href = '/admin/login.html';
}


// 左侧菜单
function leftMenu(){
    var uinfo = getAdminInfo();
    if (!uinfo) { return; }
    var formData = {
        uid: uinfo.uid,
        role_id: uinfo.role_id,
        is_leader: uinfo.is_leader,
    };
    $.ajax({
        type: apiMethod,
        url: apiDomain + 'leftmenu',
        data: formData,
        success: function (res) {
            console.log(res);
            if (res.code < 0) {
                layerMsgErr(res.msg);
                return
            }
            leftMenuHtml(res.data);
        },
        error: function () {
            console.log('网络错误');
        }
    });
}
//左侧菜单字符串
function leftMenuHtml(e){
    var preUrl = window.location.pathname; //当前相对路径
    //console.log(e);
    var ms = e;
    var h = '', i, link;
    var crumb_pname = '', crumb_name = ''; //面包屑
    h += '<style type="text/css">.mlyjt { margin-right: 10px; float: right; } .mla { background: #ffffff; }</style>';
    h += '<div>';
    h += '<dl>';
    h += '<dt>';
    h += '<a href="/admin/index.html">';
    h += '<i class="Hui-iconfont">&#xe61a;</i>';
    h += ' &nbsp; 首页';
    h += '<i class="Hui-iconfont menu_dropdown-arrow">&#xe6d5;</i>';
    h += '</a>';
    h += '</dt>';
    h += '</dl>';
    for (i = 0; i < ms.length; i ++) {
        childs = ms[i].childs;
        h += '<dl>';
        h += '<dt>';
        h += '<i class="Hui-iconfont">' + ms[i].icon + '</i>';
        h += ' &nbsp;' + ms[i].title;
        h += '</dt>';
        h += '</a>';
        h += '<dd style="display: block;">';
        h += '<ul>';
        var childs = ms[i].childs;
        for (var ii = 0; ii < childs.length; ii ++) {
            link = childs[ii].link;
            h += '<li>';
            if (preUrl == link) {
                h += '<a href="' + link + '" class="mla">';
                if (crumb_pname == '') {
                    crumb_pname = ms[i].title;
                }
                if (crumb_name == '') {
                    crumb_name = childs[ii].title;
                }
            } else {
                h += '<a href="' + link + '">';
            }
            h += childs[ii].title;
            if (preUrl == link) {
                h += '<span class="mlyjt">→</span>';
            }
            h += '</a>';
            h += '</li>';
        }
        h += '</ul>';
        h += '</dd>';
        h += '</dt>';
        h += '';
        h += '</dl>';
    }
    h += '<div style="height: 50px;"></div>';
    h += '</div>';
    $('#leftMenu').html(h);
    $('#crumb_pname').html(crumb_pname);
    $('#crumb_name').html(crumb_name);
    $('#item_name').html(config.item_name);
}


//分页字符串
function pageHtml(e){
    console.log(e);
    var start = e.start, limit = e.limit, total = e.total, url = e.url;
    var pageTotal = Math.ceil(total / limit);
    var h = '';
    h += '<style type="text/css"> #pageHtml {margin: 10px 0; width: 100%; text-align: center; color: #555; } #pageBtn {  color:#555; } #pageBtn a { padding: 5px 10px; color: #0088cc; } </style>';
    h += '显示 <span id="pageCurr">' + start + '</span> / <span id="pageTotal">' + pageTotal + '</span> 页，';
    h += '<span id="pageBtn">';
    h += '<a href="javascript:;" onclick="pageHome();">首页</a>';
    h += '<a href="javascript:;" onclick="pagePre();">上一页</a>';
    //h += '<a href="javascript:;" onclick="msgPop({msg: \'当前第' + start + '页\'});">' + start + '</a>';
    h += '<a href="javascript:;" onclick="pageNext();">下一页</a>';
    h += '<a href="javascript:;" onclick="pageEnd();">尾页</a>';
    h += '</span>';
    $('#pageHtml').html(h);
}
//首页
function pageHome(){
    var p = '?start=1';
    p += pasByUrl();
    window.location.href = pages.url + p;
}
//上一页
function pagePre(){
    //var start = pages.start * 1 - 1;
    var start = getParamByUrl('start');
    start = start ? start : pages.start;
    start = start * 1 - 1;
    if (start == 0) {
        msgPop({msg: '已经是第一页了'});
        return
    }
    window.location.href = pages.url + '?start=' + start + pasByUrl();
}
//下一页
function pageNext(){
    //var start = pages.start * 1 + 1;
    var start = getParamByUrl('start');
    start = start ? start : pages.start;
    start = start * 1 + 1;
    var pageTotal = Math.ceil(pages.total / pages.limit);
    console.log(start, pages);
    if (start > pageTotal) {
        msgPop({msg: '已经是最后一页了'});
        return
    }
    window.location.href = pages.url + '?start=' + start + pasByUrl();
}
//尾页
function pageEnd(){
    var pageTotal = Math.ceil(pages.total / pages.limit);
    window.location.href = pages.url + '?start=' + pageTotal + pasByUrl();
}
// 获取参数
function pasByUrl(){
    var depart_id = getParamByUrl('depart_id');
    var staff_id = getParamByUrl('staff_id');
    var year_id = getParamByUrl('year_id');
    var month_id = getParamByUrl('month_id');
    var sort_id = $('#sort_id').val();
    depart_id = depart_id ? depart_id : 0;
    staff_id = staff_id ? staff_id : 0;
    year_id = year_id ? year_id : 0;
    month_id = month_id ? month_id : 0;
    sort_id = sort_id ? sort_id : 0;
    return '&jstime=' + new Date().getTime() 
            + '&depart_id=' + depart_id 
            + '&staff_id=' + staff_id
            + '&year_id=' + year_id
            + '&month_id=' + month_id
            + '&sort_id=' + sort_id;
}


//抓图
function uploadImage() {
    var fileObj = $('#bigUpload')[0],
        reader = new FileReader();
    reader.readAsDataURL(fileObj.files[0]); //这一步是关键
    reader.onload = function (res){
        //console.log(res.target.result);
        showImg({img: res.target.result});
    }
}


//登录aid
function getAid(){
    var adminInfo = getAdminInfo();
    if (!adminInfo) {
        msgPop({msg: '没有登录'});
        setTimeout(function () {
            location.href = '/ad369/login.html';
        }, 1000);
        return
    }
    return adminInfo.aid;
}


//自定义弹窗
function msgPop(e){
    var cw = document.documentElement.clientWidth;
    var ch = document.documentElement.clientHeight;
    var msg = e.msg;
    var h = '';
    h += '<div style="position: fixed; top: 0; left: 0; z-index: 10000;">';
    h += '<div style="width: ' + (cw) + 'px; height: ' + (ch) + 'px; background: #000; opacity: 0.2; position: fixed; top: 0; left: 0; z-index: 10000;"></div>';
    h += '<div style="padding: 10px 20px; width: ' + (cw * 0.5) + 'px; text-align: center; background: #000; color: #FFF; border-radius: 5px; position: fixed; bottom: 30%; left: ' + ((cw * 0.5 - 40) / 2) + 'px; z-index: 10000;">'+msg+'</div>';
    h += '</div>';
    h += '<script>setTimeout(function(){$(\'#msgPop\').html(\'\');}, 2000)</script>';
    $('#msgPop').html(h);
}


//layer弹窗
function layerMsgErr(e){
    layer.msg(e,{icon: 0,time: 1000});
    return
}


//layer弹窗
function layerMsgOk(e){
    layer.msg(e,{icon: 1,time: 1000});
    return
}


//获取登录信息
function getAdminInfo(){
    return getCache(adminLogin);
}


//设置登录信息
function setAdminInfo(e){
    return setCache({key: adminLogin, val: e.val});
}


//获取地址栏中参数
function getParamByUrl(name){
    var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if(r==null) return '';
    return  unescape(r[2]);
}


//设置缓存
function setCache(e){
    var key = e.key, val = JSON.stringify(e.val);
    window.localStorage.setItem(key, val);
}


//获取缓存
function getCache(key){
    var cache = window.localStorage.getItem(key);
    if (!cache) { return ''; }
    return JSON.parse(cache);
}


//删除指定缓存
function delCache(e){
    var key = e.key;
    window.localStorage.removeItem(key);
}


//清理缓存
function clearCache(){
    window.localStorage.clear();
}